package applications

import (
	"awesome-devops/applications/backend"
	"awesome-devops/applications/backend/modules/services"
	"awesome-devops/applications/nodes"
	"awesome-devops/applications/rpc/server"
	"awesome-devops/applications/scheduler"
	"awesome-devops/applications/tools"
	"awesome-devops/boot"
	"awesome-devops/helper"
	"fmt"
	"gitee.com/jjawesomejj/awesome-util/config"
	"gitee.com/jjawesomejj/awesome-util/echo"
	"gitee.com/jjawesomejj/awesome-util/helper/commonhelper"
	"strconv"
	"strings"
	"time"
)

type Starter struct {
}

func (Starter Starter) Start() {
	helper.GetCurrentRunningPath()
	boot.Init()
	fmt.Println(helper.GetCurrentRunningPrograming())
	go backend.RunHttpServer()
	go backend.RunWsServer()
	grpcPortString := config.GetConfigByKey("rpcPort", func() interface{} {
		return "8787"
	}).(string)
	grpcPortPort, err := strconv.Atoi(grpcPortString)
	if err != nil {
		panic("rpcPort like string '8787'")
	}
	rpcServer := server.RpcServer{
		ListenPort: grpcPortPort,
	}
	role := config.GetConfigByKey("role", func() interface{} {
		return "master"
	}).(string)
	go rpcServer.Run()
	tools.GetLogger().Info("启动角色:" + role)
	if role == "master" {
		//启动主节点服务
		tools.GetLogger().Info("启动主节点服务")
		nodes.Start()
		scheduler.InitScheduler()
	}
	for true {
		time.Sleep(time.Second * 30)
	}
}

func (Starter Starter) Opssetenv() {
	value := echo.GetCmdParams()[2]
	index := strings.Index(value, "=")
	if index != -1 {
		envKey := value[:index-1]
		envValue := value[index+1:]
		helper.EchoEnv(envKey, envValue)
	}
}

func (Starter Starter) V() {
	helper.GetCurrentRunningPath()
	boot.Init()
	echo.Green(commonhelper.Format("unique_id: {}", config.GetConfigByKey("unique_id").(string)))
}

func (Starter Starter) Test() {

}

func (Starter Starter) Help() {
	echo.Yellow("command like this to init user [awesome-devops initAdmin --email=admin@qq.com --password=123456]")
}

func (Starter Starter) InitAdmin() {
	email, err := echo.GetCmdInputParamByKey("email")
	if err != nil {
		echo.Yellow("command like this to init user [awesome-devops initAdmin --email=admin@qq.com --password=123456]")
		return
	}
	password, err := echo.GetCmdInputParamByKey("password")
	if err != nil {
		echo.Yellow("command like this to init user [awesome-devops initAdmin --email=admin@qq.com --password=123456]")
		return
	}
	boot.Init()
	service := services.UserService{}
	service.InitAdminUser(email, password)
}
